<template>
  <div class="chat-container">
    <!-- 消息列表 -->
    <div class="message-list" ref="messageList">
      <div v-for="(message, index) in messages" 
           :key="index" 
           class="message"
           :class="{'user-message': message.type === 'user', 'ai-message': message.type === 'ai'}">
        <div class="message-content">
          <div v-if="message.type === 'user'" class="avatar user-avatar">You</div>
          <div v-else class="avatar ai-avatar">AI</div>
          <div class="text" v-html="message.content"></div>
        </div>
      </div>
      <div v-if="isLoading" class="message ai-message">
        <div class="message-content">
          <div class="avatar ai-avatar">AI</div>
          <div class="text">思考中...</div>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="input-container">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        type="text" 
        placeholder="输入消息..."
        :disabled="isLoading"
      >
      <button @click="sendMessage" :disabled="isLoading">发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Chat',
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      eventSource: null
    }
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return

      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: this.inputMessage
      })

      const message = this.inputMessage
      this.inputMessage = ''
      this.isLoading = true

      try {
        // 关闭之前的连接
        if (this.eventSource) {
          this.eventSource.close()
        }

        // 创建新的EventSource连接
        this.eventSource = new EventSource(`/api/chat/stream?message=${encodeURIComponent(message)}`)
        
        // 添加AI消息占位
        const aiMessageIndex = this.messages.length
        this.messages.push({
          type: 'ai',
          content: ''
        })

        // 处理消息事件
        this.eventSource.addEventListener('message', (event) => {
          if (event.data === '[DONE]') {
            this.eventSource.close()
            this.isLoading = false
            return
          }
          
          // 更新AI回复内容
          const aiMessage = this.messages[aiMessageIndex]
          aiMessage.content += event.data
          this.scrollToBottom()
        })

        // 处理错误事件
        this.eventSource.addEventListener('error', (event) => {
          this.eventSource.close()
          this.isLoading = false
          const aiMessage = this.messages[aiMessageIndex]
          aiMessage.content = '发生错误，请重试'
          console.error('SSE Error:', event)
        })

      } catch (error) {
        console.error('Error:', error)
        this.isLoading = false
        this.messages.push({
          type: 'ai',
          content: '发生错误，请重试'
        })
      }
      
      this.scrollToBottom()
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$refs.messageList
        messageList.scrollTop = messageList.scrollHeight
      })
    }
  },

  beforeDestroy() {
    // 组件销毁时关闭EventSource连接
    if (this.eventSource) {
      this.eventSource.close()
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  align-items: flex-start;
  max-width: 80%;
}

.user-message .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin: 0 10px;
  flex-shrink: 0;
}

.user-avatar {
  background-color: #4a90e2;
  color: white;
}

.ai-avatar {
  background-color: #42b983;
  color: white;
}

.text {
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message .text {
  background-color: #4a90e2;
  color: white;
  border-radius: 12px 12px 0 12px;
}

.ai-message .text {
  background-color: white;
  color: #333;
  border-radius: 12px 12px 12px 0;
}

.input-container {
  padding: 20px;
  background-color: white;
  border-top: 1px solid #e8e8e8;
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
}

input:focus {
  border-color: #4a90e2;
}

button {
  padding: 0 20px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background-color: #357abd;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style> 